#include "stdafx.h"

#include "TxtLog.h"
#include "../String.h"
#include "../Converter.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


#ifndef _DEBUG_LOG

TxtLog::~TxtLog()
{
}

void TxtLog::warning(const String & str, const char *szFile, const int nLine)
{
}

void TxtLog::message(const String & str, const char *szFile, const int nLine)
{
}
void TxtLog::error(const String & str, const char *szFile, const int nLine)
{
}

TxtLog::TxtLog(const String & fname, const String & header):
	file(0)
{
}

#else


TxtLog::~TxtLog()
{

//	EnterCriticalSection(&m_cs);
	if( file )
	{
		fputs( "---------------------Loging stopped------------------------------\n", file );
		fclose( file ); file = 0;
	}
//	LeaveCriticalSection(&m_cs);

//	DeleteCriticalSection(&m_cs);

}

void TxtLog::PutMessage(const String& str)
{
	if( file )
	{
		fprintf( file, "%s\n", str.c_str() );
		fflush( file );
	}
	TRACE0( str.c_str() );
}
void TxtLog::warning(const String & str, const char *szFile, const int nLine)
{

	Lock lock(LOCKARGS(this));
	String strPut;
	Converter::format(strPut, "%s(%d): Warning: ",  szFile, nLine);
	strPut += str;
	strPut += "\n";
	PutMessage(strPut);
}

void TxtLog::message(const String & str, const char *szFile, const int nLine)
{
	Lock lock(LOCKARGS(this));

	String strPut;
	Converter::format(strPut, "%s(%d): Message: ",  szFile, nLine);
	strPut += str;
	strPut += "\n";
	PutMessage(strPut);

}
void TxtLog::error(const String & str, const char *szFile, const int nLine)
{
	Lock lock(LOCKARGS(this));
	String strPut;
	Converter::format(strPut, "%s(%d): ERROR: ",  szFile, nLine);
	strPut += str;
	strPut += "\n";
	PutMessage(strPut);
}

TxtLog::TxtLog(const String & fname, const String & header)
:	file( fopen( fname.c_str(), "wt" ) )
{
	Lock lock(LOCKARGS(this));
//	InitializeCriticalSection(&m_cs);
	if( file )
	{
		fputs( header.c_str(), file );
		fputs( "\n", file );
		fputs( "---------------------Loging started------------------------------\n", file );
		fflush( file );
	}
}
#endif